package com.cwd.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.cwd.constant.MessageConstant;
import com.cwd.constant.RedisConstant;
import com.cwd.entity.PageResult;
import com.cwd.entity.QueryPageBean;
import com.cwd.entity.Result;
import com.cwd.pojo.Setmeal;
import com.cwd.service.SetmealService;
import com.cwd.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @PackageName: com.cwd.controller
 * @ClassName: SetmealController
 * @Author: CWD
 * @Date: 2020/3/4 12:40
 * @Description:
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    //使用JedisPool操作Redis
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private SetmealService setmealService;
    
    //上传图片
    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile){
        //获取图片的原始全名称（包括后缀）
        String originalFilename = imgFile.getOriginalFilename();
        //截取后缀名，并给图片赋新名称
        int index = originalFilename.lastIndexOf(".");//拿到索引
        String substring = originalFilename.substring(index - 1);//获取后缀名， -1是为了拿到.
        String fileName = UUID.randomUUID().toString()+substring; //新名称
        try {
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    //添加检查套餐
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal , Integer[] checkgroupIds){
        try {
            setmealService.add(setmeal,checkgroupIds);
            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
    }

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageResult pageResult = setmealService.findPage(queryPageBean);
        return pageResult;
    }
}
